/*
 * $Id: DIYClientExample.java,v 1.7 2009/01/06 07:18:19 hyyang Exp $
 * $Revision: 1.7 $
 * $Date: 2009/01/06 07:18:19 $
 */

package mlink.esms.api.diyclient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

/**
 * Mlink��������javaʾ�� <br>
 * <Ul>
 * <Li>��ʾ���弸������������Ϣ��ʹ�÷���</Li>
 * <Li>��ʾ��֧�� jre1.4 �����ϰ汾</Li>
 * <Li>��ʾ����5�ڳ�jre lib֮���jar��</Li>
 * </Ul>
 * @author hyyang
 * @since 1.4
 */
public class DIYClientExample {

    private String mtUrl="http://esms.etonenet.com/sms/mt";

    /**
     * �����
     * @param args
     */
    public static void main(String[] args) {
        DIYClientExample test = new DIYClientExample();
        try {
            //���Ե�������
            test.testSingleMt();
            test.testMultiMt();
            test.testMultiXMt();
            test.testBatchMt();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * ��������ʾ��
     */
    public void testSingleMt() {
        //�������SP��š�SP���룬�������
        String command = "MT_REQUEST";
        String spid = "****";
        String sppassword = "****";
        //sp������룬��ѡ����Ĭ��Ϊ 00
        String spsc = "00";
        //Դ���룬��ѡ����
        String sa = "10657109053657";
        //Ŀ����룬�������
        String da = "8613811111111";
        //���������Լ������ʽ���������
        int dc = 15;
        String sm = encodeHexStr(dc, "���,������ͨ���絥�����в��Զ���");//�������ݽ���Hex���룬�˴�dc��Ϊ15����ʹ��GBK�����ʽ

        //���url�ַ�
        String smsUrl = mtUrl + "?command=" + command + "&spid=" + spid + "&sppassword=" + sppassword + "&spsc=" + spsc + "&sa=" + sa + "&da=" + da + "&sm=" + sm + "&dc=" + dc;

        //����http���󣬲�����http��Ӧ
        String resStr = doGetRequest(smsUrl.toString());
        System.out.println(resStr);

        //������Ӧ�ַ�
        HashMap pp = parseResStr(resStr);
        System.out.println(pp.get("command"));
        System.out.println(pp.get("spid"));
        System.out.println(pp.get("mtmsgid"));
        System.out.println(pp.get("mtstat"));
        System.out.println(pp.get("mterrcode"));
    }

    /**
     * ��ͬ����Ⱥ��ʾ��
     */
    public void testMultiMt() {
        //�������SP��š�SP���룬�������
        String command = "MULTI_MT_REQUEST";
        String spid = "****";
        String sppassword = "****";
        //sp������룬��ѡ����Ĭ��Ϊ 00
        String spsc = "00";
        //Դ���룬��ѡ����
        String sa = "10657109053657";
        //Ŀ������飬�������
        String das = "8613811111111,8613011111111";
        //���������Լ������ʽ���������
        int dc = 15;
        String sm = encodeHexStr(dc, "���,������ͨ������ͬ����Ⱥ�����Զ���");//�������ݽ���Hex���룬�˴�dc��Ϊ15����ʹ��GBK�����ʽ

        //���url�ַ�
        String smsUrl = mtUrl + "?command=" + command + "&spid=" + spid + "&sppassword=" + sppassword + "&spsc=" + spsc + "&sa=" + sa + "&das=" + das + "&sm=" + sm + "&dc=" + dc;

        //����http���󣬲�����http��Ӧ
        String resStr = doGetRequest(smsUrl.toString());
        System.out.println(resStr);

        //������Ӧ�ַ�
        HashMap pp = parseResStr(resStr);
        System.out.println(pp.get("command"));
        System.out.println(pp.get("spid"));
        System.out.println(pp.get("mtmsgids"));
        System.out.println(pp.get("mtstat"));
        System.out.println(pp.get("mterrcode"));
    }

    /**
     * ��ͬ����Ⱥ��ʾ��
     */
    public void testMultiXMt() {
        //�������SP��š�SP���룬�������
        String command = "MULTIX_MT_REQUEST";
        String spid = "****";
        String sppassword = "****";
        //sp������룬��ѡ����Ĭ��Ϊ 00
        String spsc = "00";
        //Դ���룬��ѡ����
        String sa = "10657109053657";
        //�����ʽ���������
        int dc = 15;
        //���к��롢�����б�
        StringBuffer dasms = new StringBuffer();
        dasms.append("8613811111111/");
        dasms.append(encodeHexStr(dc, "���,������ͨ���粻ͬ����Ⱥ�����Զ���1"));
        dasms.append(",8613011111111/");
        dasms.append(encodeHexStr(dc, "���,������ͨ���粻ͬ����Ⱥ�����Զ���2"));

        //���url�ַ�
        String smsUrl = mtUrl + "?command=" + command + "&spid=" + spid + "&sppassword=" + sppassword + "&spsc=" + spsc + "&sa=" + sa + "&dasm=" + dasms.toString() + "&dc=" + dc;

        //����http���󣬲�����http��Ӧ
        String resStr = doPostRequest(smsUrl.toString());
        System.out.println(resStr);

        //������Ӧ�ַ�
        HashMap pp = parseResStr(resStr);
        System.out.println(pp.get("command"));
        System.out.println(pp.get("spid"));
        System.out.println(pp.get("mtmsgids"));
        System.out.println(pp.get("mtstat"));
        System.out.println(pp.get("mterrcode"));
    }

    /**
     * �ļ�Ⱥ��ʾ��
     * @throws UnsupportedEncodingException 
     */
    public void testBatchMt() throws UnsupportedEncodingException {
        //�������SP��š�SP���룬�������
        String command = "BATCH_MT_REQUEST";
        String spid = "****";
        String sppassword = "****";
        //sp������룬��ѡ����Ĭ��Ϊ 00
        String spsc = "00";
        //�����ţ���ѡ����
        int taskid = 10001;

        //*/��ͬ�����ļ�Ⱥ��
        int bmttype = 1;
        String title = java.net.URLEncoder.encode("abc,������ͬ�����ļ�Ⱥ��", "GBK");
        int dc = 15;
        String content = encodeHexStr(dc, "��ã�������ͨ������ͬ�����ļ�Ⱥ�����Զ���");//�������ݽ���Hex���룬�˴�dc��Ϊ15����ʹ��GBK�����ʽ
        String fileurl = "http://10.8.1.103:9001/testxiangtong.txt";
        //*/

        /*/��ͬ�����ļ�Ⱥ��
        int bmttype = 2;
        String title = java.net.URLEncoder.encode("abc,���Բ�ͬ�����ļ�Ⱥ��", "GBK");
        int dc = 15;
        String content = "";//�˴�content���ÿ�
        String fileurl = "http://10.8.1.103:9001/testbutong.txt";
        //*/

        /*/��̬ģ���ļ�Ⱥ����
        int bmttype = 3;
        String title = java.net.URLEncoder.encode("abc,���Զ�̬ģ���ļ�Ⱥ��", "GBK");
        int dc = 15;
        String content = encodeHexStr(dc, "��ã�������ͨ���綯̬ģ��Ⱥ�����Զ��ţ�ռλ���Բ���#p_1#��#p_2#");//�������ݽ���Hex���룬�˴�dc��Ϊ15����ʹ��GBK�����ʽ
        String fileurl = "http://10.8.1.103:9001/testdongtai2.txt";
        //*/

        //�����ѡ����
        int priority = 1;//    ���ȼ�
        //String attime = "20081028163000";//  ��ʱ����ʱ�䣬��ʽyyyyMMddHHmmss
        //String validtime = "20081028173000";//   ��Чʱ�䣬��ʽyyyyMMddHHmmss

        //���url�ַ�
        String smsUrl = mtUrl + "?command=" + command + "&spid=" + spid + "&sppassword=" + sppassword + "&spsc=" + spsc + "&taskid=" + taskid + "&bmttype=" + bmttype + "&title=" + title + "&dc=" + dc + "&content=" + content + "&url=" + fileurl + "&priority=" + priority;

        //����http���󣬲�����http��Ӧ
        String resStr = doGetRequest(smsUrl.toString());
        System.out.println(resStr);

        //������Ӧ�ַ�
        HashMap pp = parseResStr(resStr);
        System.out.println(pp.get("command"));
        System.out.println(pp.get("spid"));
        System.out.println(pp.get("bmtmsgid"));
        System.out.println(pp.get("mtstat"));
        System.out.println(pp.get("mterrcode"));
    }

    //���´���Ϊ����Ĺ��߷���������ɵ�����һ������н��ж���

    /**
     * ����http GET���󣬲�����http��Ӧ�ַ�
     * 
     * @param urlstr ���������url�ַ�
     * @return
     */
    public static String doGetRequest(String urlstr) {
        String res = null;
        try {
            URL url = new URL(urlstr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("Content-Type", "text/html; charset=GB2312");
            System.setProperty("sun.net.client.defaultConnectTimeout", "5000");//jdk1.4�������,l�ӳ�ʱ
            System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //jdk1.4�������,�r���ʱ
            //httpConn.setConnectTimeout(5000);//jdk 1.5�������,l�ӳ�ʱ
            //httpConn.setReadTimeout(10000);//jdk 1.5�������,�r���ʱ
            httpConn.setDoInput(true);
            int rescode = httpConn.getResponseCode();
            if (rescode == 200) {
                BufferedReader bfw = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                res = bfw.readLine();
            } else {
                res = "Http request error code :" + rescode;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return res;
    }

    /**
     * ����http POST���󣬲�����http��Ӧ�ַ�
     * 
     * @param urlstr ���������url�ַ�
     * @return
     */
    public static String doPostRequest(String urlstr) {
        String res = null;
        try {
            URL url = new URL(urlstr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setRequestProperty("Content-Type", "text/html; charset=GB2312");
            System.setProperty("sun.net.client.defaultConnectTimeout", "5000");//jdk1.4�������,l�ӳ�ʱ
            System.setProperty("sun.net.client.defaultReadTimeout", "10000"); //jdk1.4�������,�r���ʱ
            //httpConn.setConnectTimeout(5000);//jdk 1.5�������,l�ӳ�ʱ
            //httpConn.setReadTimeout(10000);//jdk 1.5�������,�r���ʱ
            httpConn.setDoInput(true);
            int rescode = httpConn.getResponseCode();
            if (rescode == 200) {
                BufferedReader bfw = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                res = bfw.readLine();
            } else {
                res = "Http request error code :" + rescode;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return res;
    }
    
    /**
     * �� �������� ������Ӧ�ַ����һ��HashMap��
     * @param resStr
     * @return
     */
    public static HashMap parseResStr(String resStr) {
        HashMap pp = new HashMap();
        try {
            String[] ps = resStr.split("&");
            for (int i = 0; i < ps.length; i++) {
                int ix = ps[i].indexOf("=");
                if (ix != -1) {
                    pp.put(ps[i].substring(0, ix), ps[i].substring(ix + 1));
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return pp;
    }


    /** 
     * Hex�����ַ���
     */
    private static final char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * ����ͨ�ַ�ת����Hex�����ַ�
     * 
     * @param dataCoding �����ʽ��15��ʾGBK���룬8��ʾUnicodeBigUnmarked���룬0��ʾISO8859-1����
     * @param realStr ��ͨ�ַ�
     * @return Hex�����ַ�
     */
    public static String encodeHexStr(int dataCoding, String realStr) {
        String hexStr = null;

        if (realStr != null) {
            byte[] data = null;
            try {
                if (dataCoding == 15) {
                    data = realStr.getBytes("GBK");
                } else if ((dataCoding & 0x0C) == 0x08) {
                    data = realStr.getBytes("UnicodeBigUnmarked");
                } else {
                    data = realStr.getBytes("ISO8859-1");
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println(e.toString());
            }

            if (data != null) {
                int len = data.length;
                char[] out = new char[len << 1];
                // two characters form the hex value.
                for (int i = 0, j = 0; i < len; i++) {
                    out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
                    out[j++] = DIGITS[0x0F & data[i]];
                }
                hexStr = new String(out);
            }
        }
        return hexStr;
    }
    
    /**
     * ��Hex�����ַ�ԭ����ͨ�ַ�
     * 
     * @param dataCoding �������ʽ��15��ʾGBK���룬8��ʾUnicodeBigUnmarked���룬0��ʾISO8859-1����
     * @param hexStr Hex�����ַ�
     * @return ��ͨ�ַ�
     */
    public static String decodeHexStr(int dataCoding, String hexStr) {
        String realStr = null;

        if (hexStr != null) {
            char[] data = hexStr.toCharArray();

            int len = data.length;

            if ((len & 0x01) != 0) {
                throw new RuntimeException("Odd number of characters.");
            }

            byte[] out = new byte[len >> 1];

            // two characters form the hex value.
            for (int i = 0, j = 0; j < len; i++) {
                int f = Character.digit(data[j], 16) << 4;
                if(f==-1){
                    throw new RuntimeException("Illegal hexadecimal charcter " + data[j] + " at index " + j);
                }
                j++;
                f = f | Character.digit(data[j], 16);
                if(f==-1){
                    throw new RuntimeException("Illegal hexadecimal charcter " + data[j] + " at index " + j);
                }
                j++;
                out[i] = (byte) (f & 0xFF);
            }
            try {
                if (dataCoding == 15) {
                    realStr = new String(out, "GBK");
                } else if ((dataCoding & 0x0C) == 0x08) {
                    realStr = new String(out, "UnicodeBigUnmarked");
                } else {
                    realStr = new String(out, "ISO8859-1");
                }
            } catch (UnsupportedEncodingException e) {
                System.out.println(e.toString());
            }
        }

        return realStr;
    }

}
